package com.publiccms.common.view;

import static com.publiccms.common.tools.SiteUtils.expose;
import static freemarker.ext.servlet.FreemarkerServlet.KEY_INCLUDE;
import static org.apache.commons.lang3.ArrayUtils.isNotEmpty;

import java.util.Enumeration;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.view.freemarker.FreeMarkerView;

import com.publiccms.logic.component.SiteComponent;

import freemarker.ext.servlet.IncludePage;

/**
 * 
 * InitializeFreeMarkerView
 *
 */
public class InitializeFreeMarkerView extends FreeMarkerView {
    protected static final String CONTEXT_ADMIN = "admin";
    protected static final String CONTEXT_USER = "user";
    protected static final String CONTEXT_BASE = "base";
    public static SiteComponent siteComponent;
    public static Pattern UNSAFE_PATTERN = Pattern.compile("_.*|get.*");

    protected void renderMergedTemplateModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        dealRequestParamters(model, request);
        model.put(KEY_INCLUDE, new IncludePage(request, response));
        super.renderMergedTemplateModel(model, request, response);
    }

    protected void exposeHelpers(Map<String, Object> model, HttpServletRequest request) throws Exception {
        model.put(CONTEXT_BASE,
                getBasePath(request.getScheme(), request.getServerName(), request.getServerPort(), request.getContextPath()));
        expose(model, siteComponent.getSiteId(request.getServerName(), request.getServerPort()));
        super.exposeHelpers(model, request);
    }

    private String getBasePath(String scheme, String serverName, int serverPort, String contextPath) {
        return scheme + "://" + (80 == serverPort ? serverName : serverName + ":" + serverPort + contextPath);
    }

    private void dealRequestParamters(Map<String, Object> model, HttpServletRequest request) {
        Enumeration<String> parameters = request.getParameterNames();
        while (parameters.hasMoreElements()) {
            String paramterName = parameters.nextElement();
            String[] values = request.getParameterValues(paramterName);
            if (isNotEmpty(values) && !UNSAFE_PATTERN.matcher(paramterName).matches()) {
                if (1 < values.length) {
                    model.put(paramterName, values);
                } else {
                    model.put(paramterName, values[0]);
                }
            }
        }
    }
}